import { useState, useCallback } from 'react'

export function useKafkaTopics() {
  const [topics, setTopics] = useState<string[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const loadTopics = useCallback(async () => {
    setLoading(true)
    setError(null)
    
    try {
      const response = await fetch('/api/kafka/topics')
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const data = await response.json()
      // 后端直接返回字符串数组，不是 {topics: string[]} 格式
      setTopics(Array.isArray(data) ? data : [])
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to load topics'
      setError(errorMessage)
      console.error('Failed to load topics:', err)
    } finally {
      setLoading(false)
    }
  }, [])

  return {
    topics,
    loading,
    error,
    loadTopics
  }
}
